<template>
    <div class="category-auctions">
        <div class="category-header" v-if="category">
            <h2>{{ category.name }}</h2>
            <p v-if="category.description">{{ category.description }}</p>
        </div>

        <!-- 筛选和排序 -->
        <div class="filter-bar">
            <el-form :inline="true" :model="filterForm">
                <el-form-item label="价格区间">
                    <el-input v-model="filterForm.minPrice" placeholder="最低价" class="price-input" />
                    <span class="separator">-</span>
                    <el-input v-model="filterForm.maxPrice" placeholder="最高价" class="price-input" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="filterForm.status" placeholder="拍卖状态" clearable>
                        <el-option label="进行中" value="ACTIVE" />
                        <el-option label="即将开始" value="PENDING" />
                        <el-option label="已结束" value="FINISHED" />
                    </el-select>
                </el-form-item>
                <el-form-item label="排序">
                    <el-select v-model="filterForm.sort" placeholder="排序方式">
                        <el-option label="默认排序" value="default" />
                        <el-option label="价格从低到高" value="priceAsc" />
                        <el-option label="价格从高到低" value="priceDesc" />
                        <el-option label="热度排序" value="popular" />
                        <el-option label="即将结束" value="ending" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="applyFilter">筛选</el-button>
                    <el-button @click="resetFilter">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 拍卖品列表 -->
        <div class="auction-list" v-loading="loading">
            <el-empty description="暂无拍卖品" v-if="auctionList.length === 0"></el-empty>

            <div v-else class="auction-grid">
                <el-card v-for="item in auctionList" :key="item.id" class="auction-card"
                    @click="viewAuctionDetail(item.id)">
                    <div class="auction-image">
                        <img :src="item.image || 'https://via.placeholder.com/300x200'" alt="拍品图片" />
                        <div class="auction-status" :class="getStatusClass(item.status)">
                            {{ getStatusText(item.status) }}
                        </div>
                    </div>
                    <div class="auction-info">
                        <h3 class="auction-title">{{ item.title }}</h3>
                        <div class="auction-price">
                            <span class="label">当前价:</span>
                            <span class="price">￥{{ item.currentPrice || item.startPrice }}</span>
                        </div>
                        <div class="auction-time">
                            <span class="label">结束时间:</span>
                            <span>{{ formatDate(item.endTime) }}</span>
                        </div>
                        <div class="auction-bid-count">
                            <span class="label">出价次数:</span>
                            <span>{{ item.bidCount || 0 }}次</span>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container" v-if="auctionList.length > 0">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
                :page-sizes="[12, 24, 36, 48]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="total" />
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAuctionsByCategory, } from '@/api/auction'
import { getUserCategoryList } from '@/api/category'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const category = ref(null)
const auctionList = ref([])
const page = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 筛选表单
const filterForm = reactive({
    minPrice: '',
    maxPrice: '',
    status: '',
    sort: 'default'
})

// 获取分类信息
const fetchCategoryInfo = async () => {
    try {
        const res = await getUserCategoryList()
        if (res && Array.isArray(res)) {
            const categoryId = Number(route.params.categoryId)
            category.value = res.find(item => item.id === categoryId) || null
            console.log('找到分类信息:', category.value)
        }
    } catch (error) {
        console.error('获取分类信息失败:', error)
    }
}

// 获取分类下的拍卖品
const fetchCategoryAuctions = async () => {
    loading.value = true
    try {
        const categoryId = route.params.categoryId
        console.log('正在获取分类ID为', categoryId, '的拍卖品')

        // 构建请求参数
        const params = {
            page: page.value,
            pageSize: pageSize.value
        }

        // 添加价格筛选条件
        if (filterForm.minPrice) {
            params.minPrice = filterForm.minPrice
        }
        if (filterForm.maxPrice) {
            params.maxPrice = filterForm.maxPrice
        }

        // 添加状态筛选条件
        if (filterForm.status) {
            params.status = filterForm.status
        }

        // 添加排序条件
        if (filterForm.sort && filterForm.sort !== 'default') {
            params.sort = filterForm.sort
        }

        console.log('发送请求参数:', { categoryId, ...params });
        const res = await getAuctionsByCategory(categoryId, params)
        console.log('获取到的拍卖品数据:', res)

        // 处理响应数据
        if (res && Array.isArray(res)) {
            auctionList.value = res
            total.value = res.length
            console.log('处理后的拍卖品数据(数组):', auctionList.value)
        } else if (res && res.data && Array.isArray(res.data)) {
            auctionList.value = res.data
            total.value = res.total || res.data.length
            console.log('处理后的拍卖品数据(对象中的数组):', auctionList.value)
        } else if (res && res.code === 1 && res.data && Array.isArray(res.data)) {
            // 处理标准的Result<List>格式
            auctionList.value = res.data
            total.value = res.data.length
            console.log('处理后的拍卖品数据(Result中的数据):', auctionList.value)
        } else {
            console.log('没有获取到拍卖品数据或格式不符合预期')
            auctionList.value = []
            total.value = 0
        }
    } catch (error) {
        console.error('获取分类拍卖品失败:', error)
        ElMessage.error('获取拍卖品列表失败，请稍后再试')
        auctionList.value = []
    } finally {
        loading.value = false
    }
}

// 应用筛选条件
const applyFilter = () => {
    page.value = 1
    fetchCategoryAuctions()
}

// 重置筛选条件
const resetFilter = () => {
    filterForm.minPrice = ''
    filterForm.maxPrice = ''
    filterForm.status = ''
    filterForm.sort = 'default'
    page.value = 1
    fetchCategoryAuctions()
}

// 查看拍卖详情
const viewAuctionDetail = (id) => {
    console.log('Clicked auction card with ID:', id); // Add this line
    router.push(`/market/auction/${id}`)
}

// 获取状态文本
const getStatusText = (status) => {
    const statusMap = {
        'PENDING': '即将开始',
        'ACTIVE': '正在进行',
        'FINISHED': '已结束',
        'CANCELLED': '已取消'
    }
    return statusMap[status] || '未知'
}

// 获取状态样式类
const getStatusClass = (status) => {
    const statusMap = {
        'PENDING': 'status-pending',
        'ACTIVE': 'status-active',
        'FINISHED': 'status-finished',
        'CANCELLED': 'status-cancelled'
    }
    return statusMap[status] || ''
}

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return '未知'
    const date = new Date(dateStr)
    return date.toLocaleString()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
    pageSize.value = val
    fetchCategoryAuctions()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
    page.value = val
    fetchCategoryAuctions()
}

// 监听路由参数变化
watch(() => route.params.categoryId, (newId, oldId) => {
    if (newId !== oldId) {
        fetchCategoryInfo()
        fetchCategoryAuctions()
    }
})

onMounted(() => {
    fetchCategoryInfo()
    fetchCategoryAuctions()
})
</script>

<style scoped>
.category-auctions {
    padding-bottom: 40px;
}

.category-header {
    margin-bottom: 20px;
}

.category-header h2 {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
}

.category-header p {
    color: #606266;
    line-height: 1.6;
}

.filter-bar {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.price-input {
    width: 120px;
}

.separator {
    margin: 0 5px;
}

.auction-list {
    margin-top: 20px;
}

.auction-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(270px, 1fr));
    gap: 20px;
}

.auction-card {
    cursor: pointer;
    transition: transform 0.3s;
}

.auction-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.auction-image {
    position: relative;
    height: 180px;
    overflow: hidden;
}

.auction-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.auction-status {
    position: absolute;
    top: 10px;
    right: 10px;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    color: #fff;
}

.status-active {
    background-color: #67c23a;
}

.status-pending {
    background-color: #909399;
}

.status-finished {
    background-color: #e6a23c;
}

.status-cancelled {
    background-color: #f56c6c;
}

.auction-info {
    padding: 15px 10px;
}

.auction-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    color: #303133;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.auction-price,
.auction-time,
.auction-bid-count {
    margin-bottom: 5px;
    font-size: 14px;
    color: #606266;
}

.label {
    color: #909399;
    margin-right: 5px;
}

.price {
    color: #f56c6c;
    font-weight: bold;
}

.pagination-container {
    margin-top: 30px;
    text-align: center;
}
</style>